<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2017/6/1
 * Time: 16:29
 */

namespace app\models;


use app\librarys\DbCacheUtility;
use app\librarys\FileService;
use app\librarys\Tools;

class File
{
    const BaseDataFolder = 'base-data';//基础数据文件，如纸张等
    const ProductFolder = 'product';//产品数据文件
    const LeagueFolder = 'league';//加盟商数据文件
    const MallProductFolder = 'mall-product';//商城产品数据文件

    /**
     * 保存图片
     * @param $file
     * @return bool|string
     */
    public static function uploadImage($file, $folder = null)
    {
        $file_name = $file['name'];
        $file_type = $file['type'];
        $file_size = $file['size'] / 1024 / 1024;
        $file_path = $file['tmp_name'];


        if (!($file_type == 'image/png' || $file_type == 'image/jpeg' || $file_type == 'image/jpg' || $file_type == 'image/bmp')) {
            return false;
        }


        $file_save_name = Tools::uuid() . '.' . pathinfo($file['name'])['extension'];
        $url = FileService::uploadImage($file_path, $file_save_name, $folder);
        if ($url != '') {
            return File::saveFile($file_name, $file_type, $file_size, $url);
        }

        return '';
    }

    /**
     * 裁剪图片返回图片路径
     * @param $file
     * @param $x
     * @param $y
     * @param $w
     * @param $h
     * @param $prop_a
     * @param $prop_b
     * @return bool|string
     */
    public static function CutImage($file, $x, $y, $w, $h, $prop_a, $prop_b)
    {
        $destionation_folder = \Yii::$app->basePath . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . date('Ymd', time()) . DIRECTORY_SEPARATOR;
        if (is_dir($destionation_folder) == false) {
            mkdir($destionation_folder);
            chmod($destionation_folder, 0777);
        }
        // 获取信息
        $filename = $file['tmp_name'];
        $pinfo = pathinfo($file['name']);
//        $ftype = $pinfo['extension'];
        $ftype = getimagesize($filename)['mime'];
        $ftype = str_replace('image/', '', $ftype);
        if ($ftype != 'png') {
            $ftype = $pinfo['extension'];
        }

        // 可以在这里修改上传后的图片名字，这里一time()为命名
        $destionation = $destionation_folder . time() . "." . $ftype;
        $pinfo = pathinfo($destionation);
        if (!move_uploaded_file($filename, $destionation)) {
            echo "移动文件出错";
            exit;
        }

        // 裁剪图片
        $img_r = '';
        if ($ftype == "png") {
            $img_r = imagecreatefrompng($destionation);
        } else {
            $img_r = imagecreatefromjpeg($destionation);
        }

        // 比例
        $prop_w = $prop_a / imagesx($img_r);
        $prop_h = $prop_b / imagesy($img_r);
        //获取实际的 长度 和坐标
        $img_x = $x / $prop_w;
        $img_y = $y / $prop_h;
        $img_w = $w / $prop_w;
        $img_h = $h / $prop_h;
        $dst_r = imagecreatetruecolor($img_w, $img_h);
        imagecopyresampled($dst_r, $img_r, 0, 0, $img_x, $img_y, $img_w, $img_h, $img_w, $img_h);

        if ($ftype == "png") {
            imagepng($dst_r, $destionation);
        } else {
            imagejpeg($dst_r, $destionation, 90);
        }

//        $img_content = [];
//        $img_content['name'] = $pinfo['basename'];
//        $img_content['type'] = $file['type'];
//        $img_content['size'] = $file['size'];
//        $img_content['tmp_name'] = $destionation;

        return DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . date('Ymd', time()) . DIRECTORY_SEPARATOR . $pinfo['basename'];
    }


    public static function UploadCutImage($image_path)
    {
        $image_path = \Yii::$app->basePath . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . $image_path;
        $pinfo = pathinfo($image_path);

        $img_content = [];
        $img_content['name'] = $pinfo['basename'];
        $img_content['type'] = 'image/' . $pinfo['extension'];
        $img_content['size'] = filesize($image_path);
        $img_content['tmp_name'] = $image_path;


        return self::uploadImage($img_content, File::BaseDataFolder);
    }

    /**
     * 裁剪并上传
     * @param $file
     * @param $x
     * @param $y
     * @param $w
     * @param $h
     * @param $prop_a
     * @param $prop_b
     * @return bool|string
     */
    public static function CutUploadImage($file, $x, $y, $w, $h, $prop_a, $prop_b)
    {
        $destionation_folder = \Yii::$app->basePath . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . date('Ymd', time()) . DIRECTORY_SEPARATOR;
        if (is_dir($destionation_folder) == false) {
            mkdir($destionation_folder);
            chmod($destionation_folder, 0777);
        }
        // 获取信息
        $filename = $file['tmp_name'];
        $pinfo = pathinfo($file['name']);
        $ftype = $pinfo['extension'];
//        if ($ftype == 'jpeg' ){
//            $ftype = 'jpg';
//        }
        // 可以在这里修改上传后的图片名字，这里一time()为命名
        $destionation = $destionation_folder . time() . "." . $ftype;
        $pinfo = pathinfo($destionation);
        if (!move_uploaded_file($filename, $destionation)) {
            echo "移动文件出错";
            exit;
        }

        // 裁剪图片
        $img_r = '';
        if ($ftype == "png") {
            $img_r = imagecreatefrompng($destionation);
        } else {
            $img_r = imagecreatefromjpeg($destionation);
        }

        // 比例
        $prop_w = $prop_a / imagesx($img_r);
        $prop_h = $prop_b / imagesy($img_r);
        //获取实际的 长度 和坐标
        $img_x = $x / $prop_w;
        $img_y = $y / $prop_h;
        $img_w = $w / $prop_w;
        $img_h = $h / $prop_h;
        $dst_r = imagecreatetruecolor($img_w, $img_h);
        imagecopyresampled($dst_r, $img_r, 0, 0, $img_x, $img_y, $img_w, $img_h, $img_w, $img_h);

        if ($ftype == "png") {
            imagepng($dst_r, $destionation);
        } else {
            imagejpeg($dst_r, $destionation, 90);
        }

        $img_content = [];
        $img_content['name'] = $pinfo['basename'];
        $img_content['type'] = $file['type'];
        $img_content['size'] = $file['size'];
        $img_content['tmp_name'] = $destionation;
        return self::uploadImage($img_content, File::BaseDataFolder);
    }

    /**
     * 保存文件
     * @param $file
     * @return bool|string
     */
    public static function uploadFile($file, $folder = null)
    {
        $file_name = $file['name'];
        $file_type = $file['type'];
        $file_size = $file['size'] / 1024 / 1024;
        $file_path = $file['tmp_name'];

        $file_save_name = Tools::uuid() . '.' . pathinfo($file['name'])['extension'];
        $url = FileService::uploadFile($file_path, $file_save_name, $folder);
        if ($url != '') {
            return File::saveFile($file_name, $file_type, $file_size, $url);
        }

        return '';
    }

    /**
     * 保存文件
     * @param $name
     * @param $type
     * @param $size
     * @param $url
     * @return string
     */
    public static function saveFile($name, $type, $size, $url)
    {
        $cmd = \Yii::$app->db->createCommand('INSERT INTO t_file (id, name, type, size, url)
                                        VALUES (:id, :name, :type, :size, :url)');

        $id = Tools::db_uuid();
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':name', $name);
        $cmd->bindValue(':type', $type);
        $cmd->bindValue(':size', $size);
        $cmd->bindValue(':url', $url);

        $result = DbCacheUtility::execute($cmd);
        if ($result > 0) {
            return $id;
        }
        return '';
    }

    /**
     * 获取文件
     * @param $id
     * @return array|false|null
     */
    public static function getFile($id)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM t_file WHERE id = :id');
        $cmd->bindValue(':id', $id);
        $item = DbCacheUtility::queryOne($cmd);
        if (!$item) {
            return null;
        }

        return $item;
    }
}